<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Fix extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
		$this->load->model('category_model');
		$this->load->model('goods_model');
		$this->load->model('siteproduct_model');
        $this->load->model('siteorder_model');
        $this->load->model('siteuser_model');
		$this->load->model('site_model');
    }
    
    public function fixcatgood()
    {

    }

    
    public function fixnofh()
    {

        $sql="SELECT s.sfordersn,so.* FROM `dream_sf` as s left join dream_sites_order as so on s.orderid=so.id WHERE s.orderid>0 and so.state<4 and so.id>7829 and s.sfordersn != ''";
        $this->load->database();
        $query = $this->db->query($sql);
        $items=$query->result_array();
        $succss = $fail = 0;
        foreach($items as $order)
        {
            $site=$this->site_model->getitembyid($order["siteid"]);
			loadsystemlink($site);
            if(!$this->mysite->checklink)
            {
                echo "请检查接口配置";	
                die();
            }
            else
            {
                $newdata=["shipping"=>$order["sfordersn"],"state"=>4];
                $result = $this->mysite->shiporder($order["oid"],$order["sfordersn"]);
                if($result=="ok")
                {
                    $this->siteorder_model->update($order["id"], $newdata);
                    $succss++;
                }
                elseif($result=="nolocation")
                {
                    $fail++;
                }
            }
            unset($this->mysite);
        }
        echo "success {$succss} record , failed {$fail}";
        die();
    }
    

    public function fixordertime()
    {
        $siteid=39;
        $maxid=12639;
        $where="siteid={$siteid} and id > {$maxid}";
        $orders=$this->siteorder_model->getfilter($where);
		if($orders)
		{
            $site=$this->site_model->getitembyid($siteid);
            loadsystemlink($site);
            foreach($orders as $order)
            {

                $rinfo = $this->mysite->getorderinfo(["orderid"=>$order["oid"]]);
                $newdata=["addtime"=>$rinfo["date_add"]];
            }

        }
        die("fix done");
    }

    public function reciver_order2()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$where="realname like '%".trim($info["name"])."%' and phone  like '%".trim($info["tel"])."%' and buy_ordersn=''";
        $orders=$this->siteorder_model->getfilter($where);
		if($orders)
		{
            if(count($orders)==1)
            {
                $newdata=[
                    "buy_ordersn"=>$info["oid"],
                    "buy_source"=>"aliexpress",
                ];
                if($orders[0]["state"]==2)
                {
                    $newdata["state"]=3;
                }
                $this->siteorder_model->update($orders[0]["id"], $newdata);
			    $this->json["message"]="ok";
            }
            else
            {
                $this->json["message"]="多个订单，无法匹配";
            }
			$this->sendjson();
		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}
    }

    public function reciver_order()
	{
		$info=json_decode($this->input->raw_input_stream,true);	
		$where="shipping='".$info["tracking_no"]."'";
        $orders=$this->siteorder_model->getfilter($where);
		if($orders)
		{
			$newdata=[
				"buy_ordersn"=>$info["id"],
				"buy_source"=>"aliexpress",
				"buyamount"=>$info["buyamount"],
            ];
    
			$this->siteorder_model->update($orders[0]["id"], $newdata);
			$this->json["message"]="ok";
			$this->sendjson();
		}
		else
		{
			$this->json["message"]="没有找到订单";
			$this->sendjson();
		}
    }
    

	private function sendjson()
	{
		echo json_encode($this->json,JSON_UNESCAPED_UNICODE);
		die();
    }
    
    public function resendorder()
    {
        $siteid=16;
        $site=$this->site_model->getitembyid($siteid);
        loadsystemlink($site);
        $where="siteid=16 and state=4 and shipping!=''";
        $orders=$this->siteorder_model->getfilter($where);
        $icount=0;
        foreach($orders as $order)
        {
            echo "check ".$order["ordersn"].": ";
            $result=$this->mysite->fixshiporder($order["oid"],$order["shipping"]);
            echo $result."\n";
            if($result=="ok") $icount++;
        }

        echo "total done ".$icount." orders";
        die();
    }

    private function subrebuilt($site,$group)
    {
        $fixcount=0;
        $priceruler = '0-10:plus#17||10-30:plus#19||30-50:multi#1.7||50-70:multi#1.65||70-100:multi#1.5||100-200:multi#1.35||200-300:multi#1.25||def:multi#1.2';        
        $where=" siteid=".$site["id"]." and rid in (".implode(",",$group).")";
        $products=$this->siteproduct_model->getitemsfilter($where);
        if($products)
        {
            foreach($products as $pro)
            {

                $orgpro=$this->goods_model->getbyid($pro["productid"]);
                $option=unserialize($orgpro["option"]);
                if(isset($option["vv"][0]["price"]))
                {
                    foreach($option["vv"][0]["price"] as &$pp)
                    {
                        $pp=get_price($priceruler,$pp+$orgpro["shippingfee"]);
                    }
                }
                $post=["option"=>$option,"rid"=>$pro["rid"]];
                $this->mysite->fixcombineprice($post);
                $fixcount++;
            }
        }
        return $fixcount;
    }

    public function rebuiltprice()
    {
        
        $sites=$this->site_model->getsitetype(1);
        $sitecount=count($sites);
        $scount=0;
        foreach($sites as $site)
        {
            $scount++;
            if($site["id"]!=58)
                continue;

            echo "开始检查站点".$site["name"]." ".$scount."/".$sitecount.",共有".$site["gcount"]."件产品\n";
            loadsystemlink($site);
            $rids=$this->mysite->combinepricepro();
            $total=count($rids["data"]);
            if($rids["data"])
            {
                $group=[];
                $done=0;
                foreach($rids["data"] as $k)
                {
                    if(count($group)>=500)
                    {
                        $done+=$this->subrebuilt($site,$group);
                        print($done."/".$total."...\n");
                        $group=[];
                    }
                    $group[]=$k;
                }
                if($group)
                {
                    $done+=$this->subrebuilt($site,$group);
                    print($done."/".$total."...\n");
                }
            }           
            echo "站点".$site["name"]."检查完毕,共重建了".$done." 件商品价格\n\n";
            unset($this->mysite);
        }

        echo "所有站点删除完毕";
        die();
    }

    public function appendshopifygood()

    {
        $where="siteid>43";
        $orders=$this->siteorder_model->getfilter($where);
        echo count($orders)." orders\n";
        if($orders)
        {
            foreach($orders as $k=>$o)
            {
                $products=json_decode($o["productinfo"],true);
                foreach($products as $pro)
                {

                    if(!$this->existpr($pro["rid"],$site["id"])):
                        $newdata=[
                            "siteid"=>$site["id"],
                            "productid"=>0,
                            "price"=>sprintf("%.2f",$pro["price"]),
                            "title"=>$pro["name"],
                            "rid"=>$pro["rid"],
                            "cid"=>0,
                            "sellcount"=>0,
                            "addtime"=>date("Y-m-d H:i:s"),
                            "url"=>"#",
                        ];
                        $this->siteproduct_model->create($newdata);
                    endif;

                }
            }
        }
        die("all done");
    }


    public function syncorderimage()
    {
        $where="thumb=''";
        $orders=$this->siteorder_model->getfilter($where);
        echo count($orders)." orders\n";
        if($orders)
        {
            foreach($orders as $k=>$o)
            {
                $site=$this->site_model->getitembyid($o["siteid"]);
                loadsystemlink($site);

                $products=json_decode($o["productinfo"],true);
                foreach($products as &$pro)
                {
                    $action=["action"=>"doaction","method"=>"getproimage","id"=>$pro["rid"]];
                    $url=$this->mysite->doaction($action);
                    $pro["thumb"]=$url;
                }
                $newdata=["thumb"=>$products[0]["thumb"],"productinfo"=>json_encode($products)];
                $this->siteorder_model->update($o["id"],$newdata);
                echo "update order ".$o["ordersn"]."\n";
                if(isset($orders[$k+1]) && $orders[$k+1]["siteid"]!=$o["siteid"])
                {
                    unset($this->mysite);
                }
            }
        }
        echo "all done";
        die();
    }

    public function syncproductlog()
    {
        $sites=$this->site_model->getsitetype(1);
        
        foreach($sites as $site)
        {

            echo "开始检查站点".$site["name"]."\n";
            loadsystemlink($site);
            $page=1;
            $ocount=0;
            $lasttime="";
            while(1)
            {
                $action=["action"=>"doaction","method"=>"syncproduct","page"=>$page];
                $html=$this->mysite->doaction($action);
                $result=json_decode($html,true);
                if($result)
                {
                    foreach($result as $pro)
                    {
                       if(!$this->existpr($pro["id_product"],$site["id"])):
                        $newdata=[
                            "siteid"=>$site["id"],
                            "productid"=>0,
                            "price"=>sprintf("%.2f",$pro["price"]),
                            "title"=>$pro["name"],
                            "rid"=>$pro["id_product"],
                            "cid"=>0,
                            "sellcount"=>0,
                            "addtime"=>date("Y-m-d H:i:s"),
                            "url"=>$pro["url"],
                        ];
                        $this->siteproduct_model->create($newdata);
                        endif;
                        $ocount++;
                    }
                }
                if(!$result || count($result)<500)
                {
                    break;
                }
                else
                {
                    $page++;
                }
            }
           
            echo "更新{$ocount}条商品记录 \n";      
            $this->site_model->update($site["id"],["gcount"=>$ocount]);
            unset($this->mysite);
        }

        echo "所有站点完毕";
        die();        
    }

    private function existpr($rid,$siteid)
    {
        $where=["rid"=>$rid,"siteid"=>$siteid];
        return $this->siteproduct_model->getitemkeyfilter($where);
    }

    public function syncordershipping()
    {
        $sites=$this->site_model->getsitetype(1);
        
        foreach($sites as $site)
        {

            echo "开始检查站点".$site["name"]."\n";
            loadsystemlink($site);
            $page=1;
            $ocount=0;
            $lasttime="";
            while(1)
            {
                $action=["action"=>"doaction","method"=>"syncorder","page"=>$page];
                $html=$this->mysite->doaction($action);
                $result=json_decode($html,true);
                if($result["data"])
                {
                    foreach($result["data"] as $order)
                    {
                        $utcDate = date('Y-m-d\TH:i:s\Z',strtotime($order["date_add"]));
                        $order["date_add"] = date('Y-m-d H:i:s',strtotime($utcDate)+60*60*5);
                        foreach($order["products"] as &$item)
                        {
                            $item["handler"]="/home/".$item["product_id"]."-xx.html";
                        }

                        if(!$lasttime)
                        {
                            $lasttime=$order["date_add"];
                        }
                        else if(strtotime($lasttime)<strtotime($order["date_add"]))
                        {
                            $lasttime=$order["date_add"];
                        }
                        $check=$this->siteorder_model->get_item_by_where(["siteid"=>$site["id"],"oid"=>$order["id_order"]]);
                        if($check)
                        {
                            //update_order
                        }
                        else
                        {

                            $cuinfo = $this->siteuser_model->get_item_by_where(["uid"=>$order["id_customer"],"siteid"=>$site["id"]]);
                            $newdata=[
                                "oid"=>$order["id_order"],
                                "siteid"=>$site["id"],
                                "uid"=>$order["id_customer"],
                                "state"=>$order["current_state"],
                                "ordersn"=>$order["reference"],
                                "amount"=>$order["total_paid"],
                                "thumb"=>"",
                                "realname"=>$order["firstname"]." ".$order["lastname"],
                                "phone"=>$order["phone"]." ".$order["phone_mobile"],
                                "country"=>$order["name"],
                                "countryiso"=>$order["iso_code"],
                                "provine"=>$order["stname"],
                                "zipcode"=>$order["postcode"],
                                "provineiso"=>$order["stcode"],
                                "city"=>$order["city"],
                                "address1"=>$order["address1"],
                                "address2"=>$order["address2"],
                                "email"=>$cuinfo["email"],
                                "addtime"=>$order["date_add"],
                                "shipping"=>$order["shipping"],
                                "productinfo"=>[],
                                "extra"=>$order["payment"],
                            ];
                            if(isset($order["email"]) && $order["email"])
                            {
                                $newdata["email"]=$order["email"];
                            }
                            
    
                            $sellcount=[];
                            $sitesellcount=[];
                            $goodcount=0;
                            foreach($order["products"] as $pro)
                            {
                                $row=["name"=>$pro["product_name"],"variant"=>$pro["variant"],"quantity"=>$pro["product_quantity"],"thumb"=>"","url"=>"","price"=>$pro["product_price"],"rid"=>$pro["product_id"],"siteurl"=>$site["domian"].$pro["handler"]];
                                $goodcount+=$pro["product_quantity"];
                                $row["url"]="#";
                                if(isset($pro["image"]) && $pro["image"]){                                                
                                    $row["thumb"]=$pro["image"];
                                }
                                
                                $newdata["productinfo"][]=$row;
                            }
                            $newdata["goodcount"]=$goodcount;
                            if(count($newdata["productinfo"])>0)
                            {
                                $newdata["thumb"]=$newdata["productinfo"][0]["thumb"];
                            }                                    
                            $newdata["productinfo"]=json_encode($newdata["productinfo"],JSON_UNESCAPED_UNICODE);
                            $this->siteorder_model->create($newdata);
                            $this->site_model->addocount($site["id"]);
                            $lasttime=$order["date_add"];
                           
                            $newinfo=["ordercount"=>$cuinfo["ordercount"]+1,"totalamount"=>$cuinfo["totalamount"]+$newdata["amount"]];
                            $this->siteuser_model->update($cuinfo["id"],$newinfo);
                            $ocount++;
                            
                        }
                    
                    }
                }


                if(!$result["data"] || count($result["data"])<50)
                {
                    break;
                }
                else
                {
                    $page++;
                }
            }
           
			echo "更新{$ocount}条订单状态 \n";      
            unset($this->mysite);
        }

        echo "所有站点完毕";
        die();
        
    }

    public function syncorderstate()
    {
        $sites=$this->site_model->getsitetype(1);
        foreach($sites as $site)
        {

            echo "开始检查站点".$site["name"]."\n";
            loadsystemlink($site);
            $page=1;
            $ocount=0;
            while(1)
            {
                $action=["action"=>"doaction","method"=>"synctracking","page"=>$page];
                $result=$this->mysite->doaction($action);
                $result=json_decode($result,true);
                if($result)
                {
                    foreach($result as $item)
                    {
                        $where="siteid=".$site["id"]." and state!=4 and oid=".$item["id_order"];
                        $orders=$this->siteorder_model->getfilter($where);
                        if($orders)
                        {
                            $this->siteorder_model->update($orders[0]["id"], ["state"=>4,"shipping"=>$item["tracking_number"]]);
                            $ocount++;
                        }

                    }
                }


                if(!$result || count($result)<50)
                {
                    break;
                }
                else
                {
                    $page++;
                }
            }
           
			echo "更新{$ocount}条订单状态 \n";      
            unset($this->mysite);
        }

        echo "所有站点删除完毕";
        die();

    }
    
    public function removehighprice()
    {

        $priceruler = '0-4.99:plus#17||5-9.99:formula#$price*4+7||10-14.99:formula#$price*3.5+7||15-19.99:formula#$price*3+7||20-29.99:formula#$price*2.5+7||def:formula#$price*1.9+7';

        $sites=$this->site_model->getsitetype(1);
        foreach($sites as $site)
        {

            echo "开始检查站点".$site["name"].",共有".$site["gcount"]."件产品\n";
            loadsystemlink($site);
       
            $where="siteid=".$site["id"]." and price >=1000 ";
            $sgs=$this->siteproduct_model->getitemsfilter($where);
            $icount=0;
            if($sgs)
            {
                foreach($sgs as $g)
                {
                    $icount++;
                    $this->mysite->delproduct(["rid"=>$g["rid"]]);
			        $this->siteproduct_model->delitem($g["id"]);
                }   
            }
            echo "站点".$site["name"]."检查完毕,共删除了".$icount." 件商品\n\n";
            unset($this->mysite);
        }

        echo "所有站点删除完毕";
        die();
    }

	public function getfixgoods()
	{
		$ids="id in (1578578,1221651) and source='amazon'";
		$result=[];
		$goods=$this->goods_model->getitemsfilter($ids);
		$icount=0;
		foreach($goods as $g)
		{
			$icount++;
			$result[]=["id"=>$g["id"],"url"=>$g["source_url"]];
			//if($icount>10) break;
		}

		echo json_encode($result);
		die();
	}
}
